package com.kedll.library.addimg;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;

import com.kedll.library.R;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.contants.OnItemClickListener;
import com.kedll.library.mvp.BasePresenter;
import com.kedll.library.util.MyMessageQueue;
import com.kedll.library.util.MyUtils;
import com.kedll.library.util.Parse;
import com.kedll.library.util.ToastUtil;

import java.util.ArrayList;
import java.util.Map;


public class AddImgFragmentActivity02 extends MyBaseFragmentActivity implements
        OnItemClickListener, View.OnClickListener {

    /**
     * 控件相关
     */
    private GridView gv_addimg;// 图片集列表
    private TextView tv_view;// 预览按钮
    private TextView tv_count;// 已选计数器
    private TextView tv_determine;// 确定按钮

    /**
     * 数据相关
     */
    private int width;// 屏幕宽
    private int viewWidth;// gridview内部控件宽
    private int maxImg;// 最多选择张数

    /**
     * 适配器
     */
    private AddImgAdapter02 imgAdapter;// 图片集适配器

    private ArrayList<Map<String, Object>> selectedList;// 已选图片集
    private ArrayList<Map<String, Object>> imgList;// 图片集

    /**
     * 线程相关
     */
    private MyThread myThread;

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.tv_view) {
            if (selectedList != null && selectedList.size() > 0) {
                Intent intent = new Intent(getApplicationContext(),
                        ViewImgFragmentActivity01.class);
                intent.putExtra("selectedList", selectedList);
                startActivityForResult(intent, RESULT_FIRST_USER);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
            }
        } else if (v.getId() == R.id.tv_determine) {
            if (selectedList != null && selectedList.size() > 0) {
                Intent in = new Intent();
                in.putExtra("selectedList", selectedList);
                in.putExtra("isFinish", true);
                setResult(RESULT_OK, in);
                finish();
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
            }
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        width = getWindowManager().getDefaultDisplay().getWidth();
        viewWidth = (width - MyUtils.dp2px(10 * 2)) / 3;
        imgList = (ArrayList<Map<String, Object>>) getIntent()
                .getSerializableExtra("imageList");
        maxImg = getIntent().getIntExtra("maxImg", 1);
        selectedList = (ArrayList<Map<String, Object>>) getIntent()
                .getSerializableExtra("selectedList");
        if (selectedList != null) {
            for (int i = 0; i < selectedList.size(); i++) {
                if (Parse.getInstance().parseBool(selectedList.get(i).get("isAdd"))) {
                    selectedList.remove(i--);
                }
            }
        } else {
            selectedList = new ArrayList<>();
        }

        gv_addimg = findViewById(R.id.gv_addimg);
        tv_view = findViewById(R.id.tv_view);
        tv_count = findViewById(R.id.tv_count);
        tv_determine = findViewById(R.id.tv_determine);
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        setTitle(getString(R.string.select_image));
        setTopLeftButton(R.drawable.ic_arrow_back, v -> {
            Intent in = new Intent();
            in.putExtra("selectedList", selectedList);
            setResult(RESULT_OK, in);
            finish();
            overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
        });
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragmentactivity_add_img02;
    }

    @Override
    protected void initEvent() {
        tv_view.setOnClickListener(this);
        tv_determine.setOnClickListener(this);
        tv_count.setText(selectedList.size() + "/" + maxImg);
        tv_view.setText(getString(R.string.preview_zh));
        tv_determine.setText(getString(R.string.determine));

        getData();
    }

    @Override
    protected void handlerMessage(Message msg) {
        super.handlerMessage(msg);
        switch (msg.what) {
            case MyMessageQueue.OK:
                if (imgList != null) {
                    setAdapter();
                    tv_count.setText(selectedList.size() + "/" + maxImg);
                }
                break;

            default:
                break;
        }
    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        if (gv_addimg.getAdapter() == null) {
            if (imgAdapter == null) {
                imgAdapter = new AddImgAdapter02(getApplicationContext(), viewWidth);
                imgAdapter.setOnItemClickListener(this);
                gv_addimg.setAdapter(imgAdapter);
            }
            imgAdapter.clear();
            imgAdapter.addAll(imgList);
        } else {
            imgAdapter.notifyDataSetChanged();
        }
    }

    protected void getData() {
        // TODO Auto-generated method stub
        if (!isAlive(myThread)) {
            myThread = new MyThread();
            myThread.start();
        }
    }

    /**
     * 判断线程是否活动状态
     *
     * @param thread
     * @return boolean
     */
    protected boolean isAlive(Thread thread) {
        if (thread == null) {
            return false;
        } else {
            return thread.isAlive();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent in = new Intent();
            in.putExtra("selectedList", selectedList);
            setResult(RESULT_OK, in);
            finish();
            overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);
        if (arg0 == RESULT_FIRST_USER) {
            if (arg1 == RESULT_OK) {
                selectedList = (ArrayList<Map<String, Object>>) arg2
                        .getSerializableExtra("selectedList");
                if (arg2.getBooleanExtra("isFinish", false)) {
                    Intent in = new Intent();
                    in.putExtra("selectedList", selectedList);
                    in.putExtra("isFinish", true);
                    setResult(RESULT_OK, in);
                    finish();
                    overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
                    return;
                }
                if (!isAlive(myThread)) {
                    myThread = new MyThread();
                    myThread.start();
                }
            }
        }
    }

    @Override
    public void itemClick(View v, Map<String, Object> item, int position) {
        if (v.getId() == R.id.rl_selected) {
            for (int i = 0; i < selectedList.size(); i++) {
                if (Parse.getInstance().isNull(selectedList.get(i).get("imagePath"))
                        .equals(Parse.getInstance().isNull(
                                item.get("imagePath")))) {
                    selectedList.remove(i--);
                }
            }
            item.put("isCheck", false);
        } else if (v.getId() == R.id.iv_img) {
            if (selectedList.size() >= maxImg) {
                ToastUtil.showToast("最多只能选择 " + maxImg + " 张哦");
                return;
            }
            item.put("isCheck", true);
            selectedList.add(0, item);
        }
        imgAdapter.notifyDataSetChanged();
        tv_count.setText(selectedList.size() + "/" + maxImg);
    }

    /**
     * 设置已选中相册的方法
     */
    private synchronized void setSelectedList() {
        for (int i = 0; i < imgList.size(); i++) {
            imgList.get(i).put("isCheck", false);
            for (int j = 0; j < selectedList.size(); j++) {
                if (Parse.getInstance().isNull(imgList.get(i).get("imagePath"))
                        .equals(Parse.getInstance().isNull(
                                selectedList.get(j).get("imagePath")))) {
                    if (Parse.getInstance()
                            .parseBool(selectedList.get(j).get("isCheck"))) {
                        imgList.get(i).put("isCheck", true);
                    } else {
                        imgList.get(i).put("isCheck", false);
                        if (!Parse.getInstance().parseBool(
                                selectedList.get(j).get("isAdd"))) {
                            selectedList.remove(j--);
                        }
                    }
                }
            }
        }
        if (handler != null) {
            handler.sendEmptyMessage(MyMessageQueue.OK);
        }
    }

    /**
     * 设置已选中相册的线程
     */
    class MyThread extends Thread {
        @Override
        public void run() {
            setSelectedList();
        }
    }
}
